package com.prb.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class WeChatClient {

    private String split = "#@#";

    private Selector selector;

    public String name = "";

    SocketChannel sc;

    private Charset charset = Charset.forName("UTF-8");

    public static void main(String[] args) throws IOException {

        new WeChatClient().start( 8099);


    }

    private void start(int port) throws IOException {

        selector = Selector.open();
        sc = SocketChannel.open(new InetSocketAddress("127.0.0.1" ,port));
        sc.configureBlocking(false);
        sc.register(selector, SelectionKey.OP_READ , SelectionKey.OP_WRITE);

        System.out.println("client is start ----------");

        new Thread(new ListenerTask()).start();

        Scanner scan = new Scanner(System.in);
        while(scan.hasNextLine()) {
            String line = scan.nextLine();
            if("".equals(line)) continue; //不允许发空消息
            if("".equals(name)) {
                name = line;
                line = name+split;
            } else {
                line = name + split + line;
            }
            sc.write(charset.encode(line));//sc既能写也能读，这边是写
        }

    }

    class ListenerTask implements Runnable {

        @Override
        public void run() {
            while (true){

                try {
                    if (selector.select() == 0) continue;

                    Set selectedKeys = selector.selectedKeys();  //可以通过这个方法，知道可用通道的集合
                    Iterator keyIterator = selectedKeys.iterator();
                    while(keyIterator.hasNext()) {
                        SelectionKey sk = (SelectionKey) keyIterator.next();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        ((SocketChannel)sk.channel()).read(byteBuffer);

                        byteBuffer.flip();
                        System.out.println(charset.decode(byteBuffer));
                        keyIterator.remove();
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }


            }

        }
    }
}

